package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.model.dto.chat.ChatMessagePageDto;
import com.example.everying.model.entity.chat.ChatConversationEntity;
import com.example.everying.model.entity.content.ActivityArticle;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.model.vo.chat.ChatMessageVo;
import com.example.everying.service.chat.ChatConversationService;
import com.example.everying.service.chat.ChatMessagesService;
import com.example.everying.service.user.UserService;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class HistoryListMessageHandler implements MessageHandler {

    private static ChatMessagesService chatMessagesService;
    private static ChatConversationService chatConversationService;
    private static UserService userService;

    @Autowired
    private void setChatMessagesService(ChatMessagesService chatMessagesService,
                                        ChatConversationService chatConversationService,
                                        UserService userService) {
        HistoryListMessageHandler.chatMessagesService = chatMessagesService;
        HistoryListMessageHandler.chatConversationService = chatConversationService;
        HistoryListMessageHandler.userService = userService;
    }

    /**
     * @param session
     * @param message
     */
    @Override
    public void handle(Session session, JSONObject message) {
        log.info("历史消息");
        String userId = WebSocketChatService.getUserId(session);
        String conversationId = message.getString("conversationId");
        ChatMessagePageDto query = new ChatMessagePageDto();
        query.setUserId(userId);
        query.setConversationId(conversationId);
        query.setPage(message.getInteger("page") == null ? 1 : message.getInteger("page"));
        query.setLimit(message.getInteger("limit") == null ? 10 : message.getInteger("limit"));
        List<ChatMessageVo> messageList = chatMessagesService.getMessageList(query);
        JSONObject result = new JSONObject();
        result.put("type", "historyList");
        result.put("conversationId", conversationId);
        result.put("historyList", messageList);
        UserEntity orderUserInfo = getUserInfo(conversationId, userId);
        if (orderUserInfo != null) {
            result.put("orderUserInfo", orderUserInfo);
            result.put("isOnline", WebSocketChatService.isOnline(orderUserInfo.getId()));
        }

        WebSocketChatService.sendMessageToUserId(userId, result.toJSONString());

    }

    // 去第一天的文章的申请人
    private UserEntity getUserInfo(String conversationId, String userId, List<ChatMessageVo> messageList) {
        if (messageList.isEmpty()) {
            return null;
        }

        // 找到第一个非空的 activityArticle
        ActivityArticle firstValidArticle = messageList.stream()
                .map(ChatMessageVo::getActivityArticle)
                .filter(Objects::nonNull)
                .findFirst()
                .orElse(null);

        if (firstValidArticle == null) {
            return null;
        }

        UserEntity userInfo = null;
        String applyUserId = null;
        if (!firstValidArticle.getUserId().equals(userId)) {
            applyUserId = userId;
            userInfo = userService.getUserById(applyUserId);
        } else {
            ChatConversationEntity entity = chatConversationService.getById(conversationId);
            if (entity.getUser1Id().equals(userId)) {
                userInfo = userService.getUserById(entity.getUser2Id());
            } else if (entity.getUser2Id().equals(userId)) {
                userInfo = userService.getUserById(entity.getUser1Id());
            }
        }

        return userInfo;
    }

    private UserEntity getUserInfo(String conversationId, String userId) {
        UserEntity userInfo = null;
        ChatConversationEntity entity = chatConversationService.getById(conversationId);
        if (entity.getUser1Id().equals(userId)) {
            userInfo = userService.getUserById(entity.getUser2Id());
        } else if (entity.getUser2Id().equals(userId)) {
            userInfo = userService.getUserById(entity.getUser1Id());
        }

        return userInfo;
    }
}
